#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "i2c.h"
#include "log.h"
#include "httpd_cgi.h"

#define MCP4725_TRIGGER_I2C_ADDR       0x60
#define MCP4725_OUTPUT_I2C_ADDR        0x61

static void mcp4725_trigger_set(uint16_t value)
{
    uint8_t byte0 = (value >> 8) & 0xF;
    uint8_t byte1 = value & 0xFF;
    i2c_write_reg(MCP4725_TRIGGER_I2C_ADDR, byte0, byte1);
}

void mcp4725_trigger_set_mv(int value)
{
    int data = value * 4095 / 3300;

    if (data > 4095) {
        data = 4095;
    }
    if (data < 0) {
        data = 0;
    }
    mcp4725_trigger_set(data);
}

static void mcp4725_proc_trigger_set_dac(char *value)
{
    uint16_t val = atoi(value);

    mcp4725_trigger_set(val);
    log_printf("Dac: %d\n", val);
}
HTTPD_CGI_PARAM_DEFINE("TriggerDac", mcp4725_proc_trigger_set_dac);


static void mcp4725_output_set(uint16_t value)
{
    uint8_t byte0 = (value >> 8) & 0xF;
    uint8_t byte1 = value & 0xFF;
    i2c_write_reg(MCP4725_OUTPUT_I2C_ADDR, byte0, byte1);
}

void mcp4725_output_set_mv(int value)
{
    int data = value * 4095 / 3300;

    if (data > 4095) {
        data = 4095;
    }
    if (data < 0) {
        data = 0;
    }
    mcp4725_output_set(data);
}

static void mcp4725_proc_output_set_dac(char *value)
{
    uint16_t val = atoi(value);

    mcp4725_output_set(val);
    log_printf("OutputDac: %d\n", val);
}
HTTPD_CGI_PARAM_DEFINE("OutputDac", mcp4725_proc_output_set_dac);
